// 将时间戳转换为年月日字符串数组, 没有参数则返回当前时间的年月日字符串数组
export const timestampToArrayDate = (timestamp) => {
  let date = new Date();
  if (timestamp) {
    // 如果时间戳是10位的则*1000
    if (String(timestamp).length === 10) {
      timestamp = timestamp * 1000;
    }
    date = new Date(timestamp);
  }
  const year = String(date.getFullYear());
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return [year, month, day];
};

// 将年月日字符串数组转换为时间戳, 没有参数则返回当前时间的时间戳
export const arrayDateToTimestamp = (dateArray) => {
  let date = new Date();
  const [year, month, day] = dateArray;
  if (year && month && day) {
    date = new Date(`${year}-${month}-${day}`);
  }
  return date.getTime() / 1000;
};

// 获取当前日期时间戳
export const getCurrentTimestamp = () => {
  // 保留整数
  return Math.floor(Date.now() / 1000);
};

// 时间戳转日期字符串
export const timestampToDate = (timestamp) => {
  const date = new Date(timestamp * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

export const formatDate = (dateOrTimestamp, format = 'YYYY-MM-DD HH:mm:ss') => {
  const date = dateOrTimestamp instanceof Date ? dateOrTimestamp : new Date(dateOrTimestamp * 1000);

  // 生成补零的日期部件
  const parts = {
    YYYY: String(date.getFullYear()),
    MM: String(date.getMonth() + 1).padStart(2, '0'),
    DD: String(date.getDate()).padStart(2, '0'),
    HH: String(date.getHours()).padStart(2, '0'),
    mm: String(date.getMinutes()).padStart(2, '0'),
    ss: String(date.getSeconds()).padStart(2, '0')
  };

  // 替换格式字符串中的占位符
  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, token => parts[token]);
};